import axios from 'axios'
import router from '@/router'
import { refreshToken } from '@/api/user'
// import { getToken, delToken } from '@/utils/storage.js'
import store from '@/store'
import to from 'await-to-js' // 优化代码
// 新axios实例
export const baseURL = 'http://geek.itheima.net/'
const instance = axios.create({
  // baseURL: 'http://geek.itheima.net/',
  baseURL,
  timeout: 5000
})

// 请求拦截器
instance.interceptors.request.use(config => {
  // const token = getToken()
  const token = store.state.token
  if (token) config.headers.Authorization = `Bearer ${token}`
  return config
}, err => Promise.reject(err))

// 响应拦截器
instance.interceptors.response.use(res => res, async err => {
  if (err.response && err.response.status === 401) {
    // token失效
    // delToken()
    // 先尝试刷新token
    const [err2, res2] = await to(refreshToken(store.state.refreshToken))
    // 如果刷新失败
    if (err2) {
      store.commit('setToken', null)
      // 删除refreshToken
      store.commit('user/setRefreshToken', '')
      router.push('/login?returnUrl=' + encodeURIComponent(router.currentRoute.fullPath))
    } else {
    // 更新token
      store.commit('user/setToken', res2.data.data.token)
      // 再次发送上次失败的请求, err.config 是之前失败的请求配置
      return instance(err.config)
    }
  }
  return Promise.reject(err)
})

// 导出一个新axios实例调用接口的函数，返回值promise
export default ({ url, method = 'get', params, data, headers }) => {
  return to(instance({ url, method, params, data, headers }))
}
